#include "LightingServer.h"
#include "SimpleTemplate.h"

#include <QTcpSocket>
#include <QTextStream>

#include <QDateTime>
#include <QFile>
#include <QFileInfo>

#include "MainWindow.h"

LightingServer::LightingServer(quint16 port, QObject* parent)
	: HttpServer(port,parent)
{}
	
void LightingServer::dispatch(QTcpSocket *socket, const QStringList &path, const QStringMap &query)
{
	
	//generic404(socket,path,query);
	QString pathStr = path.join("/");
	//qDebug() << "pathStr: "<<pathStr;
	
	if(pathStr == "" || pathStr.startsWith("preset"))
	{
		SimpleTemplate tmpl("http/data/lighting.tmpl");
		
		MainWindow *mw = MainWindow::inst();
		QList<LightingPreset*> presetList = mw->presets();
		
		if(query.contains("action"))
		{
			QString action = query.value("action");
			
			int num = query.value("num").toInt();
			if(num < 0 || num >= presetList.size())
			{
				Http_Send_404(socket) 
					<< "<h1>Oops!</h1>\n"
					<< "Sorry, that isn't a valid preset number.";
				return;
			}
			
			LightingPreset *preset = presetList[num];
			
			if(action == "play_preset")
			{
				int fadeSpeed = query.value("speed").toInt();
				if(fadeSpeed > 10000)
					fadeSpeed = 10000;
				if(fadeSpeed > 0)
					mw->setFadeSpeed(fadeSpeed, true);
					
				int endValue = query.value("value").toInt();
				if(endValue > -1)
					mw->playPreset(preset, endValue);
				else
					mw->playPreset(preset);
			}
			else
			if(action == "set_preset")
			{
				int value = query.value("value").toInt();
				if(value < 0)
					value = 0;
				if(value > 255)
					value = 255;
				preset->setValue(value);
			}
			
			Http_Send_302(socket, "/");
			return;
		}
		
		
		int counter=0;
		QVariantList presets;
		foreach(LightingPreset *preset, presetList)
		{
			QVariantMap map = preset->toVariantMap();
			int perc = (int)(((double)preset->value()) / 255.0 * 100.0);
			map["perc"] = perc;
			map["on"]  = ! (perc == 0);
			
			presets << map;
			counter ++;
		}
		
		tmpl.param("presets", presets);
		
		Http_Send_Ok(socket) 
			<< tmpl.toString();
	}
	else
	if(pathStr.startsWith("data/"))
	{
		serveFile(socket,pathStr);
	}
	else
	{
		Http_Send_404(socket) 
			<< "<h1>Oops!</h1>\n"
			<< "Hey, my bad! I can't find \"<code>"<<toPathString(path,query)<<"</code>\"! Sorry!";
	}
	
}
